package com.jlcindia.struts2;

import com.opensymphony.xwork2.validator.ValidationException;
import com.opensymphony.xwork2.validator.validators.FieldValidatorSupport;
import java.util.regex.*;

public class PasswordValidator extends FieldValidatorSupport {

	private String specialCharacter;
	static Pattern digitPattern=Pattern.compile("[0-9]");
	static Pattern letterPattern=Pattern.compile("[a-zA-Z]");
	static Pattern specialCharsDefaultPattern=Pattern.compile("[!@#$]");
	
	public void validate(Object object) throws ValidationException {
		String fieldName=getFieldName();
		String fieldValue=(String)getFieldValue(fieldName, object);
		if((fieldValue!=null)&&(fieldValue.length()>=6&&fieldValue.length()<=15)){
			fieldValue=fieldValue.trim();
			Matcher digitMatcher=digitPattern.matcher(fieldValue);
			Matcher letterMatcher=letterPattern.matcher(fieldValue);
			Matcher specialCharacterMatcher;
			if(getSpecialCharacter()!=null){
				Pattern specialPattern=Pattern.compile("["+getSpecialCharacter()+"]");
				specialCharacterMatcher=specialPattern.matcher(fieldValue);
			}else{
				specialCharacterMatcher=specialCharsDefaultPattern.matcher(fieldValue);
			}
			if(!digitMatcher.find()){
				addFieldError(fieldName, object);
				
			}else if(!letterMatcher.find()){
				addFieldError(fieldName, object);
				
			}else if(!specialCharacterMatcher.find()){
				addFieldError(fieldName, object);
				
			}
		}
		

	}

	public String getSpecialCharacter() {
		return specialCharacter;
	}

	public void setSpecialCharacter(String specialCharacter) {
		this.specialCharacter = specialCharacter;
	}
	

}
